package com.hmall.search.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.domain.dto.ItemDTO;
import com.hmall.common.domain.PageDTO;
import com.hmall.search.domain.po.ItemDoc;
import com.hmall.search.domain.query.ItemPageQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {


    private final RestHighLevelClient client = new RestHighLevelClient(RestClient.
            builder(HttpHost.create("http://192.168.80.128:9200")));

    @ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO>searchById(ItemPageQuery query) throws IOException {
/*        //输入框符复合搜索
        //1.准备请求和请求参数
        SearchRequest request = new SearchRequest("items");
        //2.准备bool复合查询参数 注意这里就是看用户给什么条件来创造了！
        //使用 StrUtil.isNotBlank() 来确保字符串有实际内容（非空白）。
        //使用 StrUtil.isNotEmpty() 来确保字符串不为空。
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        if(StrUtil.isNotBlank(query.getKey())){
            //2.1关键字搜索
            bool.must(QueryBuilders.matchQuery("name", query.getKey()));
        }if(StrUtil.isNotBlank(query.getCategory())){
            //2.2 分类搜索
            bool.must(QueryBuilders.termQuery("category", query.getCategory()));
        }if(StrUtil.isNotBlank(query.getBrand())){
            //2.3 品牌搜索
            bool.must(QueryBuilders.termQuery("brand", query.getBrand()));
        }if(query.getMaxPrice() != null){
            //2.4 价格搜索
            bool.must(QueryBuilders.rangeQuery("price").lte(query.getMaxPrice()));
        }if(query.getMinPrice() != null){
            bool.must(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()));
        }
        request.source().query(bool);
        //4.排序
        if(StrUtil.isNotBlank(query.getSortBy())){
            request.source().sort(query.getSortBy(), query.getIsAsc() ? SortOrder.ASC : SortOrder.DESC);
        }else {
            request.source().sort("updateTime", query.getIsAsc() ? SortOrder.ASC : SortOrder.DESC);
        }
        //3.同级分页参数准备
        //第几个开始继承方法
        int from = query.from();
        request.source().from(from).size(query.getPageSize());
        //广告优先展示
        request.source().query(QueryBuilders.functionScoreQuery(bool,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100))
                }).boostMode(CombineFunction.MULTIPLY));*/

        //1.构造请求
        SearchRequest searchRequest = new SearchRequest("items");
        //2.构造查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //精准总数
        searchRequest.source().trackTotalHits(true);
        if (query.getKey()!=null && !"".equals(query.getKey())) {
//            searchRequest.source()
//                    .query(QueryBuilders.matchQuery("name", query.getKey()));
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        //高亮
        searchRequest.source().highlighter(
                SearchSourceBuilder.highlight()
                        .field("name")
                        .preTags("<em>")
                        .postTags("</em>")
        );
        //分页
        searchRequest.source().from(query.from()).size(query.getPageSize());//获取页数
        //排序
        if (!"".equals(query.getSortBy())){
            searchRequest.source().sort(query.getSortBy(), query.getIsAsc()? SortOrder.ASC : SortOrder.DESC);
        }else {
            searchRequest.source().sort("updateTime",query.getIsAsc()? SortOrder.ASC : SortOrder.DESC);
        }
        //分类
        if (query.getCategory()!=null && !"".equals(query.getCategory())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", query.getCategory()));
//            searchRequest.source().query(QueryBuilders.termQuery("category", query.getCategory()));
        }
        //品牌
        if (query.getBrand()!=null && !"".equals(query.getBrand())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", query.getBrand()));
//            searchRequest.source().query(QueryBuilders.termQuery("brand", query.getBrand()));
        }
        //价格
        if (query.getMinPrice()!=null && query.getMaxPrice()!=null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()));
//            searchRequest.source().query(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()));
        }


        //searchRequest.source().query(boolQueryBuilder);
        //排名 广告优先
        searchRequest.source().query(QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100))
                }).boostMode(CombineFunction.MULTIPLY));
        //排序
       /* List<OrderItem> orders = query.toMpPage("updateTime", false).getOrders();
        for (OrderItem orderItem : orders) {
            request.source().sort(orderItem.getColumn(), orderItem.isAsc() ? SortOrder.ASC : SortOrder.DESC);
        }*/
        //5.发送请求
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        //6.返回数据
        return parseQueryResponse(query, response);
    }

    @ApiOperation("聚合搜索商品")
    @PostMapping("/filters")
    public Map filters(@RequestBody ItemPageQuery query) throws IOException {
        //1.创建请求
        SearchRequest request = new SearchRequest("items");
        //2.准备查询参数 size(0)表示只需要聚合的数据不需要文档的数据
        request.source().query(QueryBuilders.matchQuery("name", query.getKey())).size(0);
        //3.对查询结果聚合，准备聚合条件参数
        String brandAgg = "brand_agg";
        String categoryAgg = "category_agg";
        request.source().aggregation(AggregationBuilders.terms(brandAgg).field("brand")).size(10)
                .aggregation(AggregationBuilders.terms(categoryAgg).field("category")).size(10);
        //4.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        //5.解析结果
        Map<String, List<String>> map = parseStatsResponse(response, brandAgg, categoryAgg);

        return map;
    }
    //过滤条件聚合
    private static Map<String, List<String>> parseStatsResponse(SearchResponse response, String brandAgg, String categoryAgg) {
        Aggregations aggregations = response.getAggregations();
        Terms brandTerms = aggregations.get(brandAgg);
        Terms categoryTerms = aggregations.get(categoryAgg);

        List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
        List<? extends Terms.Bucket> categoryBuckets = categoryTerms.getBuckets();

        ArrayList<String> brandList = new ArrayList<>();
        ArrayList<String> categoryList = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();

        for (Terms.Bucket brandBucket : brandBuckets) {
            brandList.add(brandBucket.getKeyAsString());
        }
        for (Terms.Bucket categoryBucket : categoryBuckets) {
            categoryList.add(categoryBucket.getKeyAsString());
        }
        map.put("brand", brandList);
        map.put("category", categoryList);
        return map;
    }

    private static PageDTO<ItemDTO> parseQueryResponse(ItemPageQuery query, SearchResponse response) {
        //解析返回结果
        SearchHits searchHits = response.getHits();
        assert searchHits.getTotalHits() != null;
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits= searchHits.getHits();
        List<ItemDTO> itemDTOS = new ArrayList<>();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            ItemDoc itemDoc = JSONUtil.toBean(source, ItemDoc.class);
            ItemDTO itemDTO = BeanUtil.copyProperties(itemDoc, ItemDTO.class);
            itemDTOS.add(itemDTO);
        }
        long pageSize = query.getPageSize().longValue();
        return new PageDTO<>(total, pageSize, itemDTOS);
    }

}
